/* 商品管理 */
class ProductManager {
    constructor() {
        this.products = [];
        this.currentPage = 1;
        this.pageSize = 12;
        this.hasMore = true;
        this.currentFilters = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadProducts();
    }

    bindEvents() {
        // 搜索功能
        document.getElementById('searchBtn').addEventListener('click', this.handleSearch.bind(this));
        document.getElementById('searchInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleSearch();
            }
        });

        // 分类点击
        document.querySelectorAll('.category-card').forEach(card => {
            card.addEventListener('click', () => {
                const category = card.dataset.category;
                this.filterByCategory(category);
            });
        });

        // 加载更多
        const loadMoreBtn = document.getElementById('loadMoreBtn');
        if (loadMoreBtn) {
            loadMoreBtn.addEventListener('click', this.loadMoreProducts.bind(this));
        }

        // 商品卡片点击
        document.addEventListener('click', (e) => {
            const productCard = e.target.closest('.product-card');
            if (productCard && !e.target.classList.contains('add-to-cart-btn')) {
                const productId = productCard.dataset.productId;
                this.showProductDetail(productId);
            }
        });
    }

    // 加载商品
    async loadProducts(filters = {}) {
        try {
            this.showLoading(true);
            
            let result;
            
            // 如果有搜索关键词，使用搜索API
            if (filters.keyword) {
                result = await api.searchProducts(filters.keyword, {
                    category: filters.category,
                    min_price: filters.min_price,
                    max_price: filters.max_price
                });
            } else {
                // 否则使用普通商品列表API
                const params = {
                    page: this.currentPage,
                    limit: this.pageSize
                };
                
                if (filters.category) {
                    params.category = filters.category;
                }
                
                result = await api.getProducts(params);
            }
            
            if (result.success) {
                const products = result.data.products || [];
                
                if (filters.reset || Object.keys(filters).length === 0) {
                    this.products = products;
                    this.currentPage = 1;
                } else {
                    this.products = [...this.products, ...products];
                }
                
                this.currentFilters = filters;
                this.hasMore = result.data.has_more || false;
                
                this.renderProducts();
                this.updateLoadMoreButton();
                
                // 如果是搜索，显示搜索结果信息
                if (filters.keyword) {
                    this.showNotification(`找到 ${products.length} 个相关商品`, 'success');
                }
            } else {
                console.error('加载商品失败:', result.error);
                this.showNotification('加载商品失败: ' + result.error, 'error');
            }
            
        } catch (error) {
            console.error('加载商品失败:', error);
            this.showNotification('加载商品失败: ' + error.message, 'error');
        } finally {
            this.showLoading(false);
        }
    }

    // 获取模拟商品数据
    async getMockProducts(filters = {}) {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 500));
        
        const allProducts = [
            {
                id: 'F001',
                name: '东北大米',
                price: 115.3,
                category: 'Food',
                location: '黑龙江省哈尔滨市',
                image: 'https://via.placeholder.com/300x200?text=东北大米',
                description: '优质东北大米，粒粒饱满，口感香甜'
            },
            {
                id: 'F002',
                name: '山东小麦粉',
                price: 283.6,
                category: 'Food',
                location: '山东省德州市',
                image: 'https://via.placeholder.com/300x200?text=山东小麦粉',
                description: '精选小麦粉，制作面食的优质选择'
            },
            {
                id: 'F003',
                name: '新疆葡萄干',
                price: 219.72,
                category: 'Food',
                location: '新疆维吾尔自治区',
                image: 'https://via.placeholder.com/300x200?text=新疆葡萄干',
                description: '新疆特产葡萄干，天然无添加'
            },
            {
                id: 'C001',
                name: '时尚T恤',
                price: 89.0,
                category: 'Clothing',
                location: '广东省广州市',
                image: 'https://via.placeholder.com/300x200?text=时尚T恤',
                description: '纯棉材质，舒适透气，时尚百搭'
            },
            {
                id: 'B001',
                name: '编程入门指南',
                price: 45.0,
                category: 'Book',
                location: '北京市',
                image: 'https://via.placeholder.com/300x200?text=编程入门指南',
                description: '适合初学者的编程教程，通俗易懂'
            },
            {
                id: 'E001',
                name: '智能手机',
                price: 2999.0,
                category: 'Electronic Products',
                location: '广东省深圳市',
                image: 'https://via.placeholder.com/300x200?text=智能手机',
                description: '高性能智能手机，拍照清晰，运行流畅'
            },
            {
                id: 'D001',
                name: '洗洁精',
                price: 15.8,
                category: 'Daily product',
                location: '上海市',
                image: 'https://via.placeholder.com/300x200?text=洗洁精',
                description: '温和配方，去污力强，不伤手'
            }
        ];

        // 应用过滤器
        let filteredProducts = allProducts;
        
        if (filters.category) {
            filteredProducts = filteredProducts.filter(p => p.category === filters.category);
        }
        
        if (filters.keyword) {
            const keyword = filters.keyword.toLowerCase();
            filteredProducts = filteredProducts.filter(p => 
                p.name.toLowerCase().includes(keyword) ||
                p.description.toLowerCase().includes(keyword)
            );
        }
        
        if (filters.minPrice) {
            filteredProducts = filteredProducts.filter(p => p.price >= filters.minPrice);
        }
        
        if (filters.maxPrice) {
            filteredProducts = filteredProducts.filter(p => p.price <= filters.maxPrice);
        }

        // 分页
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        
        return filteredProducts.slice(startIndex, endIndex);
    }

    // 渲染商品
    renderProducts() {
        const recommendedContainer = document.getElementById('recommendedProducts');
        const trendingContainer = document.getElementById('trendingProducts');
        
        if (recommendedContainer) {
            this.renderProductGrid(recommendedContainer, this.products);
        }
        
        if (trendingContainer) {
            // 显示热门商品（前6个）
            const trendingProducts = this.products.slice(0, 6);
            this.renderProductGrid(trendingContainer, trendingProducts);
        }
    }

    // 渲染商品网格
    renderProductGrid(container, products) {
        if (!container) return;
        
        container.innerHTML = products.map(product => this.createProductCard(product)).join('');
    }

    // 创建商品卡片
    createProductCard(product) {
        return `
            <div class="product-card" data-product-id="${product.id}">
                <div class="product-image">
                    <img src="${product.image}" alt="${product.name}" onerror="this.style.display='none'">
                    <div class="product-overlay">
                        <i class="fas fa-eye"></i>
                    </div>
                </div>
                <div class="product-info">
                    <h3 class="product-name">${product.name}</h3>
                    <div class="product-price">¥${product.price.toFixed(2)}</div>
                    <div class="product-meta">
                        <span class="product-category">${this.getCategoryName(product.category)}</span>
                        <span class="product-location">
                            <i class="fas fa-map-marker-alt"></i>
                            ${product.location}
                        </span>
                    </div>
                    <button class="add-to-cart-btn">
                        <i class="fas fa-shopping-cart"></i>
                        加入购物车
                    </button>
                </div>
            </div>
        `;
    }

    // 获取分类中文名称
    getCategoryName(category) {
        const categoryNames = {
            'Food': '食品',
            'Clothing': '服装',
            'Book': '图书',
            'Electronic Products': '电子产品',
            'Daily product': '日用品'
        };
        return categoryNames[category] || category;
    }

    // 处理搜索
    handleSearch() {
        const keyword = document.getElementById('searchInput').value.trim();
        if (keyword) {
            this.loadProducts({ keyword, reset: true });
        }
    }

    // 按分类过滤
    filterByCategory(category) {
        this.loadProducts({ category, reset: true });
        // 更新导航状态
        document.querySelectorAll('.nav-list a').forEach(link => {
            link.classList.remove('active');
        });
        document.querySelector(`[href="products.html?category=${category}"]`)?.classList.add('active');
    }

    // 加载更多商品
    loadMoreProducts() {
        this.currentPage++;
        this.loadProducts({ ...this.currentFilters, reset: false });
    }

    // 更新加载更多按钮
    updateLoadMoreButton() {
        const loadMoreBtn = document.getElementById('loadMoreBtn');
        if (loadMoreBtn) {
            loadMoreBtn.style.display = this.hasMore ? 'block' : 'none';
            loadMoreBtn.textContent = '加载更多';
        }
    }

    // 显示商品详情
    showProductDetail(productId) {
        // 跳转到商品详情页
        window.location.href = `product-detail.html?id=${productId}`;
    }

    // 显示加载状态
    showLoading(show) {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.style.display = show ? 'flex' : 'none';
        }
    }

    // 显示通知
    showNotification(message, type = 'info') {
        if (window.authManager && window.authManager.showNotification) {
            window.authManager.showNotification(message, type);
        }
    }

    // 获取商品详情
    async getProductDetail(productId) {
        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 300));
            
            const product = this.products.find(p => p.id === productId);
            if (product) {
                return { success: true, data: product };
            } else {
                return { success: false, error: '商品不存在' };
            }
        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    // 搜索商品
    async searchProducts(keyword, filters = {}) {
        try {
            const result = await api.searchProducts(keyword, filters);
            return result;
        } catch (error) {
            console.error('搜索失败:', error);
            return { success: false, error: error.message };
        }
    }

    // 获取推荐商品
    async getRecommendedProducts(userId, limit = 10) {
        try {
            // 模拟推荐算法
            const recommended = this.products.slice(0, limit);
            return { success: true, data: recommended };
        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    // 获取热门商品
    async getTrendingProducts(limit = 10) {
        try {
            // 模拟热门商品（按价格排序）
            const trending = [...this.products].sort((a, b) => b.price - a.price).slice(0, limit);
            return { success: true, data: trending };
        } catch (error) {
            return { success: false, error: error.message };
        }
    }
}

// 创建全局商品管理器实例
window.productManager = new ProductManager();
